<template>
  <a-button type="primary" @click="handleClick">
    <template #icon><icon-plus /></template>
    新建节点</a-button
  >
  <a-modal
    v-model:visible="visible"
    title="新建节点"
    title-align="start"
    @cancel="handleCancel"
    @before-ok="handleBeforeOk"
    modal-class="formModal"
  >
    <a-form ref="formRef" :model="form" style="height: 320px">
      <a-form-item field="nodeName" label="节点名称" :rules="[{ required: true, message: '请输入节点名称' }]">
        <a-input v-model="form.nodeName" placeholder="请输入节点名称" />
      </a-form-item>
      <a-form-item field="nodeCode" label="编号" :rules="[{ required: true, message: '请输入编号' }]">
        <a-input v-model="form.nodeCode" placeholder="请输入编号" />
      </a-form-item>
      <a-form-item field="injectingTime" label="入轨时间" :rules="[{ required: true, message: '请选择入轨时间' }]">
        <a-date-picker v-model="form.injectingTime" value-format="YYYY-MM-DD HH:mm:ss" />
      </a-form-item>
      <a-form-item field="color" label="颜色" :rules="[{ required: true, message: '请选择颜色' }]">
        <input type="color" v-model="form.color" id="colorWell" />
      </a-form-item>
      <a-form-item field="iconId" label="上传图片">
        <a-upload
          list-type="picture-card"
          :action="uploadFile"
          :limit="1"
          accept="image/png,image/jpg"
          :show-retry-button="false"
          :default-file-list="fileList"
          :file-list="fileList"
          image-preview
          :on-before-upload="beforeUpload"
          @exceed-limit="handleExceed"
          @success="handleAvatarSuccess"
          @error="handleAvatarError"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { ref, toRefs, defineProps, defineEmits, defineExpose, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import { apiHome } from '@/api/healthAssessment'
import { useHealthStore } from '@/store/modules/health'
const emit = defineEmits(['funCheckRadio'])
const healthStore = toRefs(useHealthStore())
const props = defineProps({
  parentId: {
    type: String,
    default: ''
  }
})
const uploadFile = computed(() => {
  return `${import.meta.env.VITE_APP_BASE_JKPG}/upload/uploadFile`
})
const visible = ref(false)
const fileList = ref([])
const formRef = ref()
const form = ref({
  id: null,
  nodeName: '',
  color: '#00c7ef',
  iconId: '',
  nodeCode: '',
  parentId: '',
  injectingTime: ''
})
// 编辑
const funEditCard = (data) => {
  handleClick()
  fileList.value = []
  form.value = {
    ...data
  }
  data.filepath && fileList.value.push({ url: healthStore.fileServer.value + data.filepath })
}
// 显示弹框
const handleClick = () => {
  form.value = {
    id: null,
    nodeName: '',
    color: '#00c7ef',
    iconId: '',
    nodeCode: '',
    parentId: '',
    injectingTime: ''
  }
  formRef.value.resetFields()
  if (!props.parentId) {
    Message.warning('请选择左侧节点！')
    return false
  }
  visible.value = true
}
// 上传限制
const beforeUpload = (file) => {
  const isJPG =
    file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/bmp'
  if (!isJPG) {
    Message.warning('请上传JPG或PNG格式的图片!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    Message.warning('上传图片大小不能超过 2MB!')
    return false
  }
  return isJPG && isLt2M
}
// 上传文件数控制 提示
const handleExceed = () => {
  Message.warning('最多上传1张图片')
}
// 图片上传成功
const handleAvatarSuccess = (res) => {
  if (res.response.code === 200) {
    Message.success('图片上传成功！')
    form.value.iconId = res.response.data.id
  }
}
// 图片上传失败
const handleAvatarError = () => {
  Message.warning('图片上传失败！')
}
// 提交
const handleBeforeOk = (done) => {
  formRef.value.validate((errors) => {
    if (!errors) {
      if (form.value.id) {
        apiHome
          .getPortraitEdit(form.value)
          .then((res) => {
            if (res.code === 200) {
              Message.success('编辑成功！')
              done()
              handleCancel()
              emit('funCheckRadio')
            } else {
              Message.error(res.message)
            }
            done(false)
          })
          .catch((res) => {
            Message.error(res.message)
            done(false)
          })
      } else {
        form.value.parentId = props.parentId
        apiHome
          .getPortraitAdd(form.value)
          .then((res) => {
            if (res.code === 200) {
              Message.success('新建成功！')
              done()
              handleCancel()
              emit('funCheckRadio')
            } else {
              Message.error(res.message)
            }
            done(false)
          })
          .catch((res) => {
            Message.error(res.message)
            done(false)
          })
      }
    } else {
      done(false)
    }
  })
}
// 取消
const handleCancel = () => {
  fileList.value = []
  visible.value = false
}
defineExpose({
  funEditCard
})
</script>
<style lang="less" scoped></style>
